package com.djakapm.swing.component.textarea;

import com.djakapm.swing.container.BorderPanel;

import javax.swing.*;
import java.awt.event.KeyListener;


public class TextAreaView extends BorderPanel {
    private JTextArea textArea;
    public JScrollPane scroller;
    private TextAreaLineNumberPanel numberBar;
    private TextAreaContentChangeListener listener;
    private boolean showLineNumber;


    public TextAreaView(){
        this.listener = new TextAreaContentChangeListener(this);
        this.createTextArea()
        .createScrollPane()
        .addLineNumber()
        .addToCenter(this.scroller);

    }

    public boolean isShowLineNumber() {
        return showLineNumber;
    }

    public TextAreaView setShowLineNumber(boolean showLineNumber) {
        this.showLineNumber = showLineNumber;
        this.numberBar.setVisible(this.showLineNumber);
        return this;
    }

    private TextAreaView createTextArea(){
        this.textArea = new JTextArea();
        this.textArea.getDocument().addDocumentListener(this.listener);
        return this;
    }

    private TextAreaView createScrollPane(){
        this.scroller = new TextAreaScrollPane();
        this.numberBar = new TextAreaLineNumberPanel();
        this.numberBar.setVisible(this.showLineNumber);
        this.scroller.getViewport().setView(new BorderPanel().addToCenter(this.textArea).addToWest(this.numberBar));
        this.scroller.getViewport().addChangeListener(this.listener);
        return this;
    }

    public int getLineCount(){
        return this.textArea.getLineCount();
    }

    public TextAreaLineNumberPanel getLineNumberPanel(){
        return this.numberBar;
    }

    public TextAreaView addLineNumber(){
        this.numberBar.setLineNumber(this.textArea.getLineCount()).addLineNumber();
        return this;
    }

    public TextAreaView removeLineNumber(){
        this.numberBar.setLineNumber(this.textArea.getLineCount()).removeLineNumber();
        return this;
    }

    public String getText(){
        return this.textArea.getText();
    }

    public void setText(String text){
        this.textArea.setText(text);
    }

    public JTextArea getComponent(){
        return this.textArea;
    }

    @Override
    public void addKeyListener(KeyListener listener){
        this.textArea.addKeyListener(listener);
    }
}
